/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.moxiu.browser;

import com.moxiu.browser.UrlInputView.StateListener;
import com.moxiu.browser.homepage.HomePage;
import com.moxiu.browser.homepage.HomePageRoot;
import com.moxiu.browser.menu.DesktopMenuAdapter;
import com.moxiu.browser.menu.DesktopMenuAdapter.ViewHolder;
import com.moxiu.browser.view.DesktopMenuGridView;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.ViewDragHelper;
import android.util.Log;
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.OvershootInterpolator;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.moxiu.browser.UrlInputView.StateListener;
import com.moxiu.browser.menu.DesktopMenuAdapter;
import com.moxiu.browser.util.Common;
import com.moxiu.browser.view.DesktopMenuGridView;
import com.moxiu.launcher.Launcher;
import com.moxiu.launcher.R;

/**
 * Ui for regular phone screen sizes
 */
public class PhoneUi extends BaseUi{
	
   private static final String LOGTAG = "PhoneUi";
    private static final int MSG_INIT_NAVSCREEN = 100;
    private NavScreen mNavScreen;
    private AnimScreen mAnimScreen;
    public NavigationBarPhone mNavigationBar;
    private int mActionBarHeight;    
    boolean mShowNav = false;      
	private float translateX;
	private float curTranslationX;
	public int isNew;

    private static final float BOTTOM_FORBID_BG_ALPHA = 0.3f;
    
    private static final float BOTTOM_PRESS_BG_ALPHA = 0.5f;
    
    private Boolean isNight=false;
    private SharedPreferences Nightpreferences;
    private Handler Nighthandler=new Handler();
    private Editor Nighteditor;
    private LinearLayout bottomcontainer;
    private View line0;
    private View Botview;
    private View mMenuLayout;

    
    /**
     * @param browser
     * @param controller
     */
    public PhoneUi(Activity browser, UiController controller) {
        super(browser, controller);
        setUseQuickControls(BrowserSettings.getInstance().useQuickControls());
        mNavigationBar = (NavigationBarPhone) mTitleBar.getNavigationBar();
        TypedValue heightValue = new TypedValue();
        browser.getTheme().resolveAttribute(
                com.android.internal.R.attr.actionBarSize, heightValue, true);
        mActionBarHeight = TypedValue.complexToDimensionPixelSize(heightValue.data,
                browser.getResources().getDisplayMetrics());       
        mCustomScreenLinearLayout.setUiController(mUiController);       
        translateX=(float) (Common.getDisplayWidth(mActivity)*0.33);
        
        
        Resources resources =mActivity.getResources();
        bottomcontainer=(LinearLayout) mCustomScreenLinearLayout.findViewById(R.id.ga_bottom_container);
        line0 = (View) mCustomScreenLinearLayout.findViewById(R.id.lin0);
        mMenuLayout = mCustomScreenLinearLayout.findViewById(R.id.bottom_menu);
        Botview=mMenuLayout.findViewById(R.id.br_bottom_menu);
        Nightpreferences = mActivity.getSharedPreferences("default_night",
				mActivity.MODE_MULTI_PROCESS);
        Nighteditor = Nightpreferences.edit();
        isNight=Nightpreferences.getBoolean("default_night", false);
        if(isNight){
        	InitopenNight();
        } else{
       	     bottomcontainer.setBackgroundColor(Color.WHITE);	 
       	     line0.setBackgroundColor(mActivity.getResources().getColor(R.color.browser_new_baseline));
	         Botview.setBackgroundColor(Color.WHITE);        	
	         mCustomScreenLinearLayout.setBackgroundColor(Color.WHITE);
        } 
    }


	@Override
    public void onDestroy() {
        hideTitleBar();
        
        super.onDestroy();
    }
	
	@Override
	public void onResume() {
		super.onResume();
		
	}
	
	@Override
	public void onPause() {
		super.onPause();
		
		
	}
	
	

    @Override
    public void editUrl(boolean clearInput, boolean forceIME) {
        if (mUseQuickControls) {
            mTitleBar.setShowProgressOnly(false);
        }
        //Do nothing while at Nav show screen.
        if (mShowNav) return;
        super.editUrl(clearInput, forceIME);
    }

    @Override
    public boolean onMenuKey() {
    	
    	super.onMenuKey();
        return true;
    }
    
    @Override
    public boolean onBackKey() {
    
        if (showingNavScreen()) {
            mNavScreen.close(mUiController.getTabControl().getCurrentPosition());
            return true;
        } /*else if (isMenuShowing()) {
        	menuColoseAnim(true);
        	return true;
        }else if (!mActiveTab.canGoBack()) {
			
        	final AlertDialog dialog = new AlertDialog.Builder(
					mActivity).create();

			View view = LayoutInflater.from(getActivity()).inflate(R.layout.br_dialog_exit, null);
			TextView cancelTextView = (TextView) view.findViewById(R.id.br_dialog_exit_cancel);
			TextView exitTextView = (TextView) view.findViewById(R.id.br_dialog_exit_exit);
			dialog.setView(view);
			cancelTextView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					
					dialog.cancel();
				}
			});
			exitTextView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					SharedPreferences sharedPreferences = BrowserSettings.getInstance().getPreferences();
					Editor editor = sharedPreferences.edit();//获取编辑器
					editor.putLong(PreferenceKeys.KEY_LAST_WEBSITE, -1);
					editor.commit();//提交修改 
					MobclickAgent.onEvent(mActivity, "Browser_exit_ZM523", "Back");	
					
					dialog.dismiss();
					mActivity.finish();
					android.os.SystemClock.sleep(2000);
					System.exit(0);
				}
			});

			dialog.show();
			return true;
        }	*/
        
        return super.onBackKey();
    }

    public boolean showingNavScreen() {
        return mNavScreen != null && mNavScreen.getVisibility() == View.VISIBLE;
    }

    @Override
    public boolean dispatchKey(int code, KeyEvent event) {
        return false;
    }

    @Override
    public void onProgressChanged(Tab tab) {
        super.onProgressChanged(tab);
        if (mNavScreen == null && getTitleBar().getHeight() > 0) {
            mHandler.sendEmptyMessage(MSG_INIT_NAVSCREEN);
        }
    }

    @Override
    protected void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what == MSG_INIT_NAVSCREEN) {
            if (mNavScreen == null) {
                mNavScreen = new NavScreen(mActivity, mUiController, this);
                mCustomViewContainer.addView(mNavScreen, COVER_SCREEN_PARAMS);
                mNavScreen.setVisibility(View.GONE);
            }
            if (mAnimScreen == null) {
                mAnimScreen = new AnimScreen(mActivity);
                // initialize bitmaps
                mAnimScreen.set(getTitleBar(), getWebView());
            }
        }
    }

    @Override
    public void setActiveTab(final Tab tab) {
        mTitleBar.cancelTitleBarAnimation(true);
        mTitleBar.setSkipTitleBarAnimations(true);
        super.setActiveTab(tab);
        Log.d("isHome", "###control setActiveTab PhoneUi : " + getHomePage().isShowing());
//        changeMulitTabNumber();
        //if at Nav screen show, detach tab like what showNavScreen() do.
        if (mShowNav) {
            detachTab(mActiveTab);
        }

        BrowserWebView view = (BrowserWebView) tab.getWebView();
        // TabControl.setCurrentTab has been called before this,
        // so the tab is guaranteed to have a webview
        if (view == null) {
            Log.e(LOGTAG, "active tab with no webview detected");
            return;
        }
        // Request focus on the top window.
        if (mUseQuickControls) {
            view.setTitleBar(null);
            mTitleBar.setShowProgressOnly(true);
        } else {
            view.setTitleBar(mTitleBar);
        }
        // update nav bar state
        mNavigationBar.onStateChanged(StateListener.STATE_NORMAL);
        updateLockIconToLatest(tab);
        mTitleBar.setSkipTitleBarAnimations(false);
        
//        if (mHomePage != null) {
//        	mHomePage.setActiveTab(tab);
//        }
        
//       changeBottomNavState(tab);
    }

    // menu handling callbacks

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        updateMenuState(mActiveTab, menu);
        return true;
    }

    @Override
    public void updateMenuState(Tab tab, Menu menu) {
//        MenuItem bm = menu.findItem(R.id.bookmarks_menu_id);
//        if (bm != null) {
//            bm.setVisible(!showingNavScreen());
//        }
//        MenuItem abm = menu.findItem(R.id.add_bookmark_menu_id);
//        if (abm != null) {
//            abm.setVisible((tab != null) && !tab.isSnapshot() && !showingNavScreen());
//        }
//        MenuItem info = menu.findItem(R.id.page_info_menu_id);
//        if (info != null) {
//            info.setVisible(false);
//        }
//        MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
//        if (newtab != null && !mUseQuickControls) {
//            newtab.setVisible(false);
//        }
//        MenuItem closeOthers = menu.findItem(R.id.close_other_tabs_id);
//        if (closeOthers != null) {
//            boolean isLastTab = true;
//            if (tab != null) {
//                isLastTab = (mTabControl.getTabCount() <= 1);
//            }
//            closeOthers.setEnabled(!isLastTab);
//        }
//        if (showingNavScreen()) {
//            menu.setGroupVisible(R.id.LIVE_MENU, false);
//            menu.setGroupVisible(R.id.SNAPSHOT_MENU, false);
//            menu.setGroupVisible(R.id.NAV_MENU, false);
//            menu.setGroupVisible(R.id.COMBO_MENU, true);
//        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        if (showingNavScreen()
//                && (item.getItemId() != R.id.history_menu_id)
//                && (item.getItemId() != R.id.snapshots_menu_id)) {
//        
//            hideNavScreen(mUiController.getTabControl().getCurrentPosition(), false);
//        }
        return false;
    }

    @Override
    public void onContextMenuCreated(Menu menu) {
        hideTitleBar();
    }

    @Override
    public void onContextMenuClosed(Menu menu, boolean inLoad) {
        if (inLoad) {
            showTitleBar();
        }
    }

    // action mode callbacks

    @Override
    public void onActionModeStarted(ActionMode mode) {
        if (!isEditingUrl()) {
            hideTitleBar();
        } else {
//            mTitleBar.animate().translationY(mActionBarHeight);
        }
    }

    @Override
    public void onActionModeFinished(boolean inLoad) {
        mTitleBar.animate().translationY(0);
        if (inLoad) {
            if (mUseQuickControls) {
                mTitleBar.setShowProgressOnly(true);
            }
            showTitleBar();
        }
    }

    @Override
    public boolean isWebShowing() {
        return super.isWebShowing() && !showingNavScreen();
    }

    @Override
    public void showWeb(boolean animate) {
        super.showWeb(animate);
        
        hideNavScreen(mUiController.getTabControl().getCurrentPosition(), animate);
    }

    void showNavScreen1() {
    	
    	UrlInputView mAutiText=mNavigationBar.getAutTextview();
    	if(mAutiText!=null)
    	mAutiText.setVisibility(View.GONE);

        mShowNav = true;
        mUiController.setBlockEvents(true);
        if (mNavScreen == null) {
            mNavScreen = new NavScreen(mActivity, mUiController, this);
            mCustomViewContainer.addView(mNavScreen, COVER_SCREEN_PARAMS);
        } else {
            mNavScreen.setVisibility(View.VISIBLE);
            mNavScreen.setAlpha(1f);
            mNavScreen.refreshAdapter();
        }
        mNavScreen.initview();
        
     
        mActiveTab.capture();
        if (mAnimScreen == null) {
            mAnimScreen = new AnimScreen(mActivity);
        } else {
            mAnimScreen.mMain.setAlpha(1f);
            mAnimScreen.mTitle.setAlpha(1f);
            mAnimScreen.setScaleFactor(1f);
        }
        mAnimScreen.set(getTitleBar(), getWebView());
        if (mAnimScreen.mMain.getParent() == null) {
            mCustomViewContainer.addView(mAnimScreen.mMain, COVER_SCREEN_PARAMS);
        }
        mCustomViewContainer.setVisibility(View.VISIBLE);
        mCustomViewContainer.bringToFront();
        mAnimScreen.mMain.layout(0, 0, mContentView.getWidth(),
                mContentView.getHeight());
        int fromLeft = 0;
        int fromTop = getTitleBar().getHeight();
        int fromRight = mContentView.getWidth();
        int fromBottom = mContentView.getHeight();
        int width = mActivity.getResources().getDimensionPixelSize(R.dimen.nav_tab_width);
        int height = mActivity.getResources().getDimensionPixelSize(R.dimen.nav_tab_height);
        int ntth = mActivity.getResources().getDimensionPixelSize(R.dimen.nav_tab_titleheight);
        int toLeft = (mContentView.getWidth() - width) / 2;
        int toTop = ((fromBottom - (ntth + height)) / 2 + ntth);
        int toRight = toLeft + width;
        int toBottom = toTop + height;
        float scaleFactor = width / (float) mContentView.getWidth();
        detachTab(mActiveTab);
        mContentView.setVisibility(View.GONE);
        AnimatorSet set1 = new AnimatorSet();
        AnimatorSet inanim = new AnimatorSet();
        ObjectAnimator tx = ObjectAnimator.ofInt(mAnimScreen.mContent, "left",
                fromLeft, toLeft);
        ObjectAnimator ty = ObjectAnimator.ofInt(mAnimScreen.mContent, "top",
                fromTop, toTop);
        ObjectAnimator tr = ObjectAnimator.ofInt(mAnimScreen.mContent, "right",
                fromRight, toRight);
        ObjectAnimator tb = ObjectAnimator.ofInt(mAnimScreen.mContent, "bottom",
                fromBottom, toBottom);
        ObjectAnimator title = ObjectAnimator.ofFloat(mAnimScreen.mTitle, "alpha",
                1f, 0f);
        ObjectAnimator sx = ObjectAnimator.ofFloat(mAnimScreen, "scaleFactor",
                1f, scaleFactor);
        ObjectAnimator blend1 = ObjectAnimator.ofFloat(mAnimScreen.mMain,
                "alpha", 1f, 0f);
        blend1.setDuration(100);

        inanim.playTogether(tx, ty, tr, tb, sx, title);
        inanim.setDuration(200);
        set1.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator anim) {
                mCustomViewContainer.removeView(mAnimScreen.mMain);
                finishAnimationIn();
                mUiController.setBlockEvents(false);
            }
        });
       // set1.playSequentially(inanim, blend1);
        set1.playSequentially(blend1, inanim);//改变进入动画
        set1.start();
    }
    
    void showNavScreen() {
    	mUiController.forceScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        int  position=mTabControl.getCurrentPosition();     
          mShowNav = true;       
          mUiController.setBlockEvents(true);
          if (mNavScreen == null) {
              mNavScreen = new NavScreen(mActivity, mUiController, this);
              mCustomViewContainer.addView(mNavScreen, COVER_SCREEN_PARAMS);
          } else {
              mNavScreen.setVisibility(View.VISIBLE);
              mNavScreen.setAlpha(1f);
              mNavScreen.refreshAdapter();
          }
          mNavScreen.initview();             
          mActiveTab.capture();
          if (mAnimScreen == null) {
              mAnimScreen = new AnimScreen(mActivity);
          } else {
              mAnimScreen.mMain.setAlpha(1f);
              mAnimScreen.mTitle.setAlpha(1f);
              mAnimScreen.setScaleFactor(1f);
          }
          mAnimScreen.set(getTitleBar(), getWebView());
          if (mAnimScreen.mMain.getParent() == null) {
              mCustomViewContainer.addView(mAnimScreen.mMain, COVER_SCREEN_PARAMS);
          }
          mCustomViewContainer.setVisibility(View.VISIBLE);
          mCustomViewContainer.bringToFront();  
          
          if(isNight){
         	 Nightlayout.bringToFront();
         }
          
          mAnimScreen.mMain.layout(0, 0, mContentView.getWidth(),
                  mContentView.getHeight());
          int fromLeft = 0;
          int fromTop = getTitleBar().getHeight();
          int fromRight = mContentView.getWidth();
          int fromBottom = mContentView.getHeight();
          int width = mActivity.getResources().getDimensionPixelSize(R.dimen.nav_tab_width);//得到其像素值，缩小后tab的宽度
          int height = mActivity.getResources().getDimensionPixelSize(R.dimen.nav_tab_height);//缩小后tab的高度
          int ntth = mActivity.getResources().getDimensionPixelSize(R.dimen.nav_tab_titleheight);//标题+XX符号的高度
          int toLeft = (mContentView.getWidth() - width) / 2;
          int toTop = ((fromBottom - (ntth + height)) / 2 + ntth);
          int toRight = toLeft + width;
          int toBottom = toTop + height;
          float scaleFactor = width / (float) mContentView.getWidth();
          detachTab(mActiveTab);
          mContentView.setVisibility(View.GONE);
          AnimatorSet set1 = new AnimatorSet();
          AnimatorSet inanim = new AnimatorSet();
          ObjectAnimator tx = ObjectAnimator.ofInt(mAnimScreen.mContent, "left",
                  fromLeft, toLeft);
          tx.setDuration(500);
           ObjectAnimator ty = ObjectAnimator.ofInt(mAnimScreen.mContent, "top",
          		 fromTop, toTop);
          ty.setDuration(1);
          ObjectAnimator tr = ObjectAnimator.ofInt(mAnimScreen.mContent, "right",
                  fromRight, toRight);
          tr.setDuration(500);
          ObjectAnimator tb = ObjectAnimator.ofInt(mAnimScreen.mContent, "bottom",
          		fromBottom, toBottom);
          tb.setDuration(1);
          ObjectAnimator title = ObjectAnimator.ofFloat(mAnimScreen.mTitle, "alpha",
                  1f, 0f);
          ObjectAnimator sx = ObjectAnimator.ofFloat(mAnimScreen, "scaleFactor",
                  1f, scaleFactor);
          ObjectAnimator blend1 = ObjectAnimator.ofFloat(mAnimScreen.mMain,
                  "alpha", 0f, 0f);
          blend1.setDuration(1);
    inanim.playTogether(tx, ty, tr, tb, sx, title);
          inanim.setDuration(200);
          set1.addListener(new AnimatorListenerAdapter() {
              @Override
              public void onAnimationEnd(Animator anim) {
                  mCustomViewContainer.removeView(mAnimScreen.mMain);
                  finishAnimationIn();
                  mUiController.setBlockEvents(false);
              }
          });    
          NavTabView tabview0 = mNavScreen.getTabView(position-3);
          NavTabView tabview1 = mNavScreen.getTabView(position-2);         
          NavTabView tabview2 = mNavScreen.getTabView(position-1); 
          NavTabView tabview3 = mNavScreen.getTabView(position);
          curTranslationX= tabview3.getTranslationX();
          NavTabView tabview4 = mNavScreen.getTabView(position+1);
          NavTabView tabview5 = mNavScreen.getTabView(position+2);
          NavTabView tabview6 = mNavScreen.getTabView(position+3);
          
          
          ObjectAnimator t7 =null;
          ObjectAnimator t6 =null;
  		ObjectAnimator t5 =null;
      	ObjectAnimator t4 =null;
      	ObjectAnimator t3 =null;
      	ObjectAnimator t2 =null;
      	ObjectAnimator t1 =null;
          	if(tabview0!=null){
          		 t1=setAnimation(tabview0);
          		 t2=setAnimation(tabview1);
          		 t3=setAnimation(tabview2);
          		 t4=setAnimation(tabview3);
          		 if(tabview6!=null){
          			 t7=setAnimation(tabview6);
          			 t6=setAnimation(tabview5);
          			 t5=setAnimation(tabview4);
          				t2.setStartDelay(30);
          	            t3.setStartDelay(60);
          	            t4.setStartDelay(90);
          	            t5.setStartDelay(120);
          	            t6.setStartDelay(150);
          	            t7.setStartDelay(180);
       set1.play(blend1).with(t1).with(t2).with(t3).with(t4).with(t5).with(t6).with(t7);			 
          		 }else if(tabview5!=null){        			 
          			 t6=setAnimation(tabview5);
          			 t5=setAnimation(tabview4);
          				t2.setStartDelay(30);
          	            t3.setStartDelay(60);
          	            t4.setStartDelay(90);
          	            t5.setStartDelay(120);
          	            t6.setStartDelay(150);
          		     set1.play(blend1).with(t1).with(t2).with(t3).with(t4).with(t5).with(t6);
          		 }else if(tabview4!=null){
          			 t5=setAnimation(tabview4);
          				t2.setStartDelay(30);
          	            t3.setStartDelay(60);
          	            t4.setStartDelay(90);
          	            t5.setStartDelay(120);
          		     set1.play(blend1).with(t1).with(t2).with(t3).with(t4).with(t5);
          		 }else{
          				t2.setStartDelay(30);
          	            t3.setStartDelay(60);
          	            t4.setStartDelay(90);
          			 set1.play(blend1).with(t1).with(t2).with(t3).with(t4);
          		 }
          	}else if(tabview1!=null){
          		 t2=setAnimation(tabview1);
          		 t3=setAnimation(tabview2);
          		 t4=setAnimation(tabview3);
          		 if(tabview6!=null){
          			 t7=setAnimation(tabview6);
          			 t6=setAnimation(tabview5);
          			 t5=setAnimation(tabview4);
          	            t3.setStartDelay(30);
          	            t4.setStartDelay(60);
          	            t5.setStartDelay(90);
          	            t6.setStartDelay(120);
          	            t7.setStartDelay(250);
       set1.play(blend1).with(t2).with(t3).with(t4).with(t5).with(t6).with(t7);			 
          		 }else if(tabview5!=null){        			 
          			 t6=setAnimation(tabview5);
          			 t5=setAnimation(tabview4);
       	            t3.setStartDelay(30);
       	            t4.setStartDelay(60);
       	            t5.setStartDelay(90);
       	            t6.setStartDelay(120);
          	set1.play(blend1).with(t2).with(t3).with(t4).with(t5).with(t6);
          		 }else if(tabview4!=null){
          			 t5=setAnimation(tabview4);
       	            t3.setStartDelay(30);
       	            t4.setStartDelay(60);
       	            t5.setStartDelay(90);
          		     set1.play(blend1).with(t2).with(t3).with(t4).with(t5);
          		 }else {
       	            t3.setStartDelay(30);
       	            t4.setStartDelay(60);
          			 set1.play(blend1).with(t2).with(t3).with(t4);
          		 }
          	}else if(tabview2!=null){
          		 t3=setAnimation(tabview2);
          		 t4=setAnimation(tabview3);
          		 if(tabview6!=null){
          			 t7=setAnimation(tabview6);
          			 t6=setAnimation(tabview5);
          			 t5=setAnimation(tabview4);
       	            t4.setStartDelay(30);
       	            t5.setStartDelay(60);
       	            t6.setStartDelay(90);
       	            t7.setStartDelay(120);
                       set1.play(blend1).with(t3).with(t4).with(t5).with(t6).with(t7);			 
          		 }else if(tabview5!=null){        			 
          			 t6=setAnimation(tabview5);
          			 t5=setAnimation(tabview4);
          			 t4.setStartDelay(30);
        	             t5.setStartDelay(60);
        	             t6.setStartDelay(90);
          		     set1.play(blend1).with(t3).with(t4).with(t5).with(t6);
          		 }else if(tabview4!=null){
          			 t5=setAnimation(tabview4);
          			 t4.setStartDelay(30);
        	             t5.setStartDelay(60);
          		     set1.play(blend1).with(t3).with(t4).with(t5);
          		 }else {
          			 t4.setStartDelay(30);
          			 set1.play(blend1).with(t3).with(t4);
          		 }
          	}else{
          		 t4=setAnimation(tabview3);
          		 if(tabview6!=null){
          			 t7=setAnimation(tabview6);
          			 t6=setAnimation(tabview5);
          			 t5=setAnimation(tabview4);
        	             t5.setStartDelay(30);
        	             t6.setStartDelay(60);
        	             t7.setStartDelay(90);
                       set1.play(blend1).with(t4).with(t5).with(t6).with(t7);			 
          		 }else if(tabview5!=null){        			 
          			 t6=setAnimation(tabview5);
          			 t5=setAnimation(tabview4);
          			 t5.setStartDelay(30);
        	             t6.setStartDelay(60);
          		     set1.play(blend1).with(t4).with(t5).with(t6);
          		 }else if(tabview4!=null){
          			 t5=setAnimation(tabview4);
          			 t5.setStartDelay(30);
          		     set1.play(blend1).with(t4).with(t5);
          		 }else {
          			 set1.play(blend1).with(t4);
          		 }
          	}        	   
          set1.start();
      }

    private void finishAnimationIn() {
        if (showingNavScreen()) {
            // notify accessibility manager about the screen change
            mNavScreen.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
            mTabControl.setOnThumbnailUpdatedListener(mNavScreen);
//            if (mHomePage.isShowing()) {
//            	mActiveTab.setHomePagePosition(mHomePage.getHomePageItemPosition());
//            }
        }
    }

    void hideNavScreen1(int position, boolean animate) { 
    	
    	UrlInputView mAutiText=mNavigationBar.getAutTextview();
    	if(mAutiText!=null)
    	mAutiText.setVisibility(View.VISIBLE);

    	
        mShowNav = false;
        if (!showingNavScreen()) return;
        final Tab tab = mUiController.getTabControl().getTab(position);
        if ((tab == null) || !animate) {
            if (tab != null) {
                setActiveTab(tab);
            } else if (mTabControl.getTabCount() > 0) {
                // use a fallback tab
                setActiveTab(mTabControl.getCurrentTab());
            }
            mContentView.setVisibility(View.VISIBLE);
            finishAnimateOut();
            return;
        }
        NavTabView tabview = (NavTabView) mNavScreen.getTabView(position);
        
        if (tabview == null) {
            if (mTabControl.getTabCount() > 0) {
                // use a fallback tab
                setActiveTab(mTabControl.getCurrentTab());
            }
            mContentView.setVisibility(View.VISIBLE);
            finishAnimateOut();
            return;
        }
        mUiController.setBlockEvents(true);
        mUiController.setActiveTab(tab);
        mContentView.setVisibility(View.VISIBLE);
        if (mAnimScreen == null) {
            mAnimScreen = new AnimScreen(mActivity);
        }
        mAnimScreen.set(tab.getScreenshot());
        if (mAnimScreen.mMain.getParent() == null) {
            mCustomViewContainer.addView(mAnimScreen.mMain, COVER_SCREEN_PARAMS);
        }
        mAnimScreen.mMain.layout(0, 0, mContentView.getWidth(),
                mContentView.getHeight());
        mNavScreen.mScroller.finishScroller();
        ImageView target = tabview.mImage;
        int toLeft = 0;
        int toTop = (tab.getWebView() != null) ? tab.getWebView().getVisibleTitleHeight() : 0;
        int toRight = mContentView.getWidth();
        int width = target.getDrawable().getIntrinsicWidth();
        int height = target.getDrawable().getIntrinsicHeight();
        int fromLeft = tabview.getLeft() + target.getLeft() - mNavScreen.mScroller.getScrollX();
        int fromTop = tabview.getTop() + target.getTop() - mNavScreen.mScroller.getScrollY();
        int fromRight = fromLeft + width;
        int fromBottom = fromTop + height;
        float scaleFactor = mContentView.getWidth() / (float) width;
        int toBottom = toTop + (int) (height * scaleFactor);
        mAnimScreen.mContent.setLeft(fromLeft);
        mAnimScreen.mContent.setTop(fromTop);
        mAnimScreen.mContent.setRight(fromRight);
        mAnimScreen.mContent.setBottom(fromBottom);
        mAnimScreen.setScaleFactor(1f);
        AnimatorSet set1 = new AnimatorSet();
        ObjectAnimator fade2 = ObjectAnimator.ofFloat(mAnimScreen.mMain, "alpha", 0f, 1f);
        ObjectAnimator fade1 = ObjectAnimator.ofFloat(mNavScreen, "alpha", 1f, 0f);
        set1.playTogether(fade1, fade2);
       // set1.setDuration(100);
        set1.setDuration(0);
        AnimatorSet set2 = new AnimatorSet();
        ObjectAnimator l = ObjectAnimator.ofInt(mAnimScreen.mContent, "left",
                fromLeft, toLeft);
        ObjectAnimator t = ObjectAnimator.ofInt(mAnimScreen.mContent, "top",
                fromTop, toTop);
        ObjectAnimator r = ObjectAnimator.ofInt(mAnimScreen.mContent, "right",
                fromRight, toRight);
        ObjectAnimator b = ObjectAnimator.ofInt(mAnimScreen.mContent, "bottom",
                fromBottom, toBottom);
        ObjectAnimator scale = ObjectAnimator.ofFloat(mAnimScreen, "scaleFactor",
                1f, scaleFactor);
        ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
        //otheralpha.setDuration(100);
        otheralpha.setDuration(0);
        set2.playTogether(l, t, r, b, scale);
        
      //  set2.setDuration(200);
        set2.setDuration(0);
        
        AnimatorSet combo = new AnimatorSet();
        combo.playSequentially(set1, set2, otheralpha);
        combo.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator anim) {
                mCustomViewContainer.removeView(mAnimScreen.mMain);
                finishAnimateOut();
                mUiController.setBlockEvents(false);
            }
        });
       combo.start();
    }
    
    void hideNavScreen(int position, boolean animate) {
    	
    	mUiController.restoreScreenAutoRotate();
        mShowNav = false;
        if (!showingNavScreen()) return;
        final Tab tab = mUiController.getTabControl().getTab(position);
        if ((tab == null) || !animate) {
            if (tab != null) {
                setActiveTab(tab);
            } else if (mTabControl.getTabCount() > 0) {
                // use a fallback tab
                setActiveTab(mTabControl.getCurrentTab());
            }
            mContentView.setVisibility(View.VISIBLE);
            finishAnimateOut();
            return;
        }
        NavTabView tabview = (NavTabView) mNavScreen.getTabView(position);
        
        if (tabview == null) {
            if (mTabControl.getTabCount() > 0) {
                // use a fallback tab
                setActiveTab(mTabControl.getCurrentTab());
            }
            mContentView.setVisibility(View.VISIBLE);
            finishAnimateOut();
            return;
        }
        mUiController.setBlockEvents(true);
        mUiController.setActiveTab(tab);
        mContentView.setVisibility(View.VISIBLE);
        if(isNight){
        mContentView.setBackgroundColor(mActivity.getResources().getColor(R.color.br_night_bg_on));
        }else{
        	mContentView.setBackgroundColor(mActivity.getResources().getColor(R.color.normal_bg));
        }
        if (mAnimScreen == null) {
            mAnimScreen = new AnimScreen(mActivity);
        }
        mAnimScreen.set(tab.getScreenshot());
        if (mAnimScreen.mMain.getParent() == null) {
            mCustomViewContainer.addView(mAnimScreen.mMain, COVER_SCREEN_PARAMS);
        }
        mAnimScreen.mMain.layout(0, 0, mContentView.getWidth(),
                mContentView.getHeight());
        mNavScreen.mScroller.finishScroller();
        ImageView target = tabview.mImage;
        int toLeft = 0;
        int toTop = (tab.getWebView() != null) ? tab.getWebView().getVisibleTitleHeight() : 0;
        int toRight = mContentView.getWidth();
        int width = target.getDrawable().getIntrinsicWidth();
        int height = target.getDrawable().getIntrinsicHeight();
        int fromLeft = tabview.getLeft() + target.getLeft() - mNavScreen.mScroller.getScrollX();
        int fromTop = tabview.getTop() + target.getTop() - mNavScreen.mScroller.getScrollY();
        int fromRight = fromLeft + width;
        int fromBottom = fromTop + height;
        float scaleFactor = mContentView.getWidth() / (float) width;
        int toBottom = toTop + (int) (height * scaleFactor);
        mAnimScreen.mContent.setLeft(fromLeft);
        mAnimScreen.mContent.setTop(fromTop);
        mAnimScreen.mContent.setRight(fromRight);
        mAnimScreen.mContent.setBottom(fromBottom);
        mAnimScreen.setScaleFactor(1f);
        AnimatorSet set1 = new AnimatorSet();
        ObjectAnimator fade2 = ObjectAnimator.ofFloat(mAnimScreen.mMain, "alpha", 0f, 1f);
        ObjectAnimator fade1 = ObjectAnimator.ofFloat(mNavScreen, "alpha", 1f, 0f);
        set1.playTogether(fade1, fade2);
       // set1.setDuration(100);
        set1.setDuration(0);
        AnimatorSet set2 = new AnimatorSet();
        ObjectAnimator l = ObjectAnimator.ofInt(mAnimScreen.mContent, "left",
                fromLeft, toLeft);
        ObjectAnimator t = ObjectAnimator.ofInt(mAnimScreen.mContent, "top",
                fromTop, toTop);
        ObjectAnimator r = ObjectAnimator.ofInt(mAnimScreen.mContent, "right",
                fromRight, toRight);
        ObjectAnimator b = ObjectAnimator.ofInt(mAnimScreen.mContent, "bottom",
                fromBottom, toBottom);
        ObjectAnimator scale = ObjectAnimator.ofFloat(mAnimScreen, "scaleFactor",
                1f, scaleFactor);
       /* ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
        //otheralpha.setDuration(100);
        otheralpha.setDuration(300);*/
        set2.playTogether(l, t, r, b, scale);        
      // set2.setDuration(200);
         set2.setDuration(0);        
         AnimatorSet combo = new AnimatorSet();
         //System.out.println("当前的tabview===="+tabview);
        /* tabview.setVisibility(View.GONE);
         tabview.setAlpha(0f);*/
//         bottomcontainer.setAlpha(1.0f);
         ObjectAnimator ScalY = ObjectAnimator.ofFloat(mContentView, "scaleY", 0.94f, 1f);
  	     ObjectAnimator ScalX = ObjectAnimator.ofFloat(mContentView, "scaleX", 0.94f, 1f);
  	     ScalY.setDuration(330);
  	     ScalX.setDuration(330);        

  	     if(isNew==2){
  	    	  mCustomViewContainer.setAlpha(0f);
  	    	  combo.play(ScalY).with(ScalX);
  	    	  isNew=0;
  	     }else if(isNew==1){
  	    	 ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
  	         otheralpha.setDuration(300);
  	         combo.play(ScalY).with(ScalX).with(otheralpha);
  	         isNew=0;
  	     }else{
  	    	ObjectAnimator otheralpha = ObjectAnimator.ofFloat(mCustomViewContainer, "alpha", 1f, 0f);
 	        otheralpha.setDuration(300);
  	    	combo.play(otheralpha);
  	     }
        combo.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator anim) {
                mCustomViewContainer.removeView(mAnimScreen.mMain);
                finishAnimateOut();
                mUiController.setBlockEvents(false);
            }
        });
       combo.start();
    }
    private void finishAnimateOut() {
        mTabControl.setOnThumbnailUpdatedListener(null);
        mNavScreen.setVisibility(View.GONE);
        mCustomViewContainer.setAlpha(1f);
        mCustomViewContainer.setVisibility(View.GONE);
        
//        changeMulitTabNumber();
//        changeMenuState(mActiveTab);
        mBottomNavigation.onTabDataChanged(mActiveTab);
    }

    @Override
    public boolean needsRestoreAllTabs() {
        return false;
    }

    public void toggleNavScreen() {
        if (!showingNavScreen()) {
            showNavScreen();
        } else {
        	
            hideNavScreen(mUiController.getTabControl().getCurrentPosition(), false);
        }
    }

    @Override
    public boolean shouldCaptureThumbnails() {
        return true;
    }

    static class AnimScreen {

        private View mMain;
        private ImageView mTitle;
        private ImageView mContent;
        private float mScale;
        private Bitmap mTitleBarBitmap;
        private Bitmap mContentBitmap;

        public AnimScreen(Context ctx) {
            mMain = LayoutInflater.from(ctx).inflate(R.layout.br_anim_screen,
                    null);
            mTitle = (ImageView) mMain.findViewById(R.id.title);
            mContent = (ImageView) mMain.findViewById(R.id.content);
            mContent.setScaleType(ImageView.ScaleType.MATRIX);
            mContent.setImageMatrix(new Matrix());
            mScale = 1.0f;
            setScaleFactor(getScaleFactor());
        }

        public void set(TitleBar tbar, WebView web) {
            if (tbar == null || web == null) {
                return;
            }
            if (tbar.getWidth() > 0 && tbar.getEmbeddedHeight() > 0) {
                if (mTitleBarBitmap == null
                        || mTitleBarBitmap.getWidth() != tbar.getWidth()
                        || mTitleBarBitmap.getHeight() != tbar.getEmbeddedHeight()) {
                    mTitleBarBitmap = safeCreateBitmap(tbar.getWidth(),
                            tbar.getEmbeddedHeight());
                }
                if (mTitleBarBitmap != null) {
                    Canvas c = new Canvas(mTitleBarBitmap);
                    tbar.draw(c);
                    c.setBitmap(null);
                }
            } else {
                mTitleBarBitmap = null;
            }
            mTitle.setImageBitmap(mTitleBarBitmap);
            mTitle.setVisibility(View.VISIBLE);
            int h = web.getHeight() - tbar.getEmbeddedHeight();
            if (mContentBitmap == null
                    || mContentBitmap.getWidth() != web.getWidth()
                    || mContentBitmap.getHeight() != h) {
                mContentBitmap = safeCreateBitmap(web.getWidth(), h);
            }
            if (mContentBitmap != null) {
                Canvas c = new Canvas(mContentBitmap);
                int tx = web.getScrollX();
                int ty = web.getScrollY();
                c.translate(-tx, -ty - tbar.getEmbeddedHeight());
                web.draw(c);
                c.setBitmap(null);
            }
            mContent.setImageBitmap(mContentBitmap);
        }

        private Bitmap safeCreateBitmap(int width, int height) {
            if (width <= 0 || height <= 0) {
                Log.w(LOGTAG, "safeCreateBitmap failed! width: " + width
                        + ", height: " + height);
                return null;
            }
            return Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        }

        public void set(Bitmap image) {
            mTitle.setVisibility(View.GONE);
            mContent.setImageBitmap(image);
        }

        private void setScaleFactor(float sf) {
            mScale = sf;
            Matrix m = new Matrix();
            m.postScale(sf,sf);
            mContent.setImageMatrix(m);
        }

        private float getScaleFactor() {
            return mScale;
        }

    }
    
    @Override
    public void onTabDataChanged(Tab tab) {

    	super.onTabDataChanged(tab);
    	
    	
    	
    	
    }
    
    
    
//    private Tab mLastActiveTab = null;
    @Override
    public void onHomePageShowStateChange(Tab tab, boolean show) {
    	super.onHomePageShowStateChange(tab, show);
    	
    	showFixTitle(false);
    	
    	
    	
    	
    }
    
    
    //=============================================
    

	
	
//	@Override
//	public void removeTab(Tab tab) {
//		super.removeTab(tab);
//		
//	}


	@Override
	public void hideBottomMenu() {
		super.hideBottomMenu();
		
	}

	
	
	public ObjectAnimator setAnimation(NavTabView tab){
		 tab.setTranslationX(translateX);
   	 ObjectAnimator ot = ObjectAnimator.ofFloat(tab, "translationX",  translateX, curTranslationX);
   	 ot.setInterpolator(new DecelerateInterpolator());                   
        ot.setDuration(500);
        return ot;
	}
    //==============================================
	
	/*夜间模式*/
	 public void addNightView() {	 		
	       if(!isNight){	
	    	   switchNight.bringToFront();
	    	   switchNight.setVisibility(View.VISIBLE);
	           switch_night_image.setBackgroundResource(R.drawable.br_switch_night);
	    	   //AnimatorSet Nightset = new AnimatorSet();
	    	   final ObjectAnimator NightAnim = ObjectAnimator.ofFloat(switch_night_image, "rotationY",180F,360F);
	    	   NightAnim.setDuration(700);
	    	   NightAnim.setInterpolator(new LinearInterpolator());
	    	   NightAnim.addListener(new AnimatorListenerAdapter() {
		             @Override
		             public void onAnimationEnd(Animator anim) {
		 
		                  Nighthandler.postDelayed(nightRunnable, 400);
		                  NightAnim.cancel();
		               }
		         }); 
	    	   NightAnim.setStartDelay(400);
	    	   NightAnim.start();
	    	   
	    	   Nightlayout.setVisibility(View.VISIBLE);
	    	   int Tabsize=mUiController.getTabs().size();
	    	   for(int i=0;i<Tabsize;i++){
	    		 Tab tab=mTabControl.getTab(i); 
	        	  if(tab!=null){
	        		 tab .OpenNight(true);	
	        	  }	   
	        	  }  	        	
	      		 isNight=true;		      		 
	      	     Nighteditor.putBoolean("default_night", true);
	      	   
	      	     openNight();
	          }else{        	  
	        	 switchNight.bringToFront();
		    	 switchNight.setVisibility(View.VISIBLE);
		    	 switch_night_image.setBackgroundResource(R.drawable.br_switch_day);
		    	   final ObjectAnimator NightAnim = ObjectAnimator.ofFloat(switch_night_image, "rotationY",0F,180F);
		    	   NightAnim.setDuration(700);
		    	   NightAnim.setInterpolator(new LinearInterpolator());
		    	   NightAnim.addListener(new AnimatorListenerAdapter() {
			             @Override
			             public void onAnimationEnd(Animator anim) {
			            
			            	 Nighthandler.postDelayed(nightRunnable, 400);
			            	 NightAnim.cancel();
			               }
			         });  
		    	   NightAnim.setStartDelay(400);
		    	   NightAnim.start();
	        	 	        	  
	        	  Nightlayout.setVisibility(View.GONE);
	        	  int Tabsize=mUiController.getTabs().size();
		    	   for(int i=0;i<Tabsize;i++){
		    		 Tab tab=mTabControl.getTab(i); 
		        	  if(tab!=null){
		        		  tab .OpenNight(false);	
		        	  }	   
		        	  }   	
	        	 isNight=false;	   
	        	 Nighteditor.putBoolean("default_night", false);
	        	
	        	 closeNight();
	        	
	          }
	       Nighteditor.commit();
		}
	   
	   public void openNight(){
		     Initnight();
	         if(mHomePage!=null){
		      	   mHomePage.mHBrowserMainManager.switchNight(true);
		      	     }
	   }
	   public void closeNight(){
		     Initclosenight();
	         if(mHomePage!=null){
	        	 mHomePage.mHBrowserMainManager.switchNight(false);
	        	 }
	   }
	   Runnable nightRunnable=new Runnable(){
		   @Override
		   public void run() {
		       	 switchNight.setVisibility(View.GONE);
		       	 
		   } 
		   };
      public void InitopenNight(){
    	         Initnight();
		         if(mHomePage!=null){
			      	mHomePage.mHBrowserMainManager.InitNight();
			      	     }
		   }  
      private void Initnight(){
    	     mBottomNavigation.NightModel(true);
		     bottomcontainer.setBackgroundColor(mActivity.getResources().getColor(R.color.br_night_bg_on));	    
		     line0.setBackgroundColor(mActivity.getResources().getColor(R.color.br_night_line));
	         Botview.setBackgroundColor(mActivity.getResources().getColor(R.color.br_night_bg_on));	
	         mNavigationBar.switchToNight(true);
	         mNavigationBar.switchToNightBase(true);
	         mTitleBar.titleBackground.setBackgroundColor(mActivity.getResources().getColor(R.color.br_night_bg));
	         mCustomScreenLinearLayout.setBackgroundColor(mActivity.getResources().getColor(R.color.br_night_bg));
             mContentView.setBackgroundColor(mActivity.getResources().getColor(R.color.br_night_bg));
      }
      private void Initclosenight(){
    	     mBottomNavigation.NightModel(false);
		     bottomcontainer.setBackgroundColor(Color.WHITE);
		     line0.setBackgroundColor(mActivity.getResources().getColor(R.color.browser_new_baseline));
	         Botview.setBackgroundColor(Color.WHITE);        	
	         mNavigationBar.switchToNight(false);
	         mNavigationBar.switchToNightBase(false);
	         mTitleBar.titleBackground.setBackgroundColor(Color.WHITE);
	         mCustomScreenLinearLayout.setBackgroundColor(Color.WHITE);
	         mContentView.setBackgroundColor(mActivity.getResources().getColor(R.color.br_menu_more));
      }     
}
